<template>
  <div>
    <a-modal
      :title="title"
      :visible="visibleStatus"
      :confirm-loading="confirmLoading"
      @ok="handleOk"
      @cancel="handleCancel"
    >

      <a-form ref="form" :form="form" :label-col="{ span: 5 }" :wrapper-col="{ span: 12 }">
        <a-form-item label="快递名称">
          <a-input
            v-decorator="['name', { rules: [{ required: true, message: '请输入快递名称' }] }]"
          />
        </a-form-item>

        <a-form-item label="序列号">
          <a-input-number
            :min=1
            :max=255
            v-decorator="['sort_id']"
          />
        </a-form-item>
      </a-form>

    </a-modal>
  </div>
</template>

<script>
  import { saveCourierCompany } from '@/api/system'

  export default {
    name: 'CourierCompanyForm',
    data () {
      return {
        title: '新建',
        confirmLoading: false,
        visibleStatus: this.visible,
        record: this.data,
        form: this.$form.createForm(this)
      }
    },
    props: {
      visible: {
        default: false,
        type: Boolean
      },
      data: {
        default: () => {
        },
        type: Object
      }
    },
    watch: {
      visible (val) {
        this.visibleStatus = val
      },
      data (val) {
        this.$nextTick(() => {
          this.$refs.form.form.setFieldsValue({ 'name': val.name, 'sort_id': val.sort_id })
        })
        this.record = val
        this.title = (val.hasOwnProperty('id') ? '编辑' : '新增') + '快递公司'
      }
    },
    methods: {
      handleOk (e) {
        this.confirmLoading = true

        this.$refs.form.form.validateFields((err, values) => {
          if (err === null) {
            if (this.record.hasOwnProperty('id')) {
              values.id = this.record.id
            }
            saveCourierCompany(values).then(res => {
              this.confirmLoading = false
              this.$emit('visible', false)
              this.$emit('refreshList')
            })
          }

          this.confirmLoading = false
        })
      },
      handleCancel (e) {
        this.$emit('visible', false)
      }
    }
  }
</script>

<style scoped>

</style>
